package com.serkol.utils;

import com.serkol.ams.bean.ImageInfo;
import com.serkol.ams.entity.PosterDevise;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;

public class ImageUtils {
    private static String AVATAR_TYPE = "avatar";
    private static String QRCODE_TYPE = "qrcode";
    private static String NICKNAME_TYPE = "nickname";
    private static String CONTENT_TYPE = "content";

    public static void main(String[] args) throws IOException {
        ImageUtils imageUtils = new ImageUtils();
        //  imageUtils.createImage();
    }

    /**
     * 设置圆角
     *
     * @param srcImage 图片
     * @param radius   圆角
     * @param border   边框
     * @param padding  内边距
     */
    public static BufferedImage setRadius(BufferedImage srcImage, int radius, int border, int padding) throws IOException {
        int width = srcImage.getWidth();
        int height = srcImage.getHeight();
        int canvasWidth = width + padding * 2;
        int canvasHeight = height + padding * 2;

        BufferedImage image = new BufferedImage(canvasWidth, canvasHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D gs = image.createGraphics();
        gs.setComposite(AlphaComposite.Src);
        gs.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        gs.setColor(Color.WHITE);
        gs.fill(new RoundRectangle2D.Float(0, 0, canvasWidth, canvasHeight, radius, radius));
        gs.setComposite(AlphaComposite.SrcAtop);
        gs.drawImage(setClip(srcImage, radius), padding, padding, null);
        if (border != 0) {
            gs.setColor(Color.GRAY);
            gs.setStroke(new BasicStroke(border));
            gs.drawRoundRect(padding, padding, canvasWidth - 2 * padding, canvasHeight - 2 * padding, radius, radius);
        }
        gs.dispose();
        return image;
    }

    /**
     * 圆角
     */
    public static BufferedImage setRadius(BufferedImage srcImage) throws IOException {
        int radius = (srcImage.getWidth() + srcImage.getHeight()) / 25;
        return setRadius(srcImage, radius, 0, 0);
    }

    /**
     * 圆角
     */
    public static BufferedImage setRadius(BufferedImage srcImage, int radius1) throws IOException {
        // int radius = (srcImage.getWidth() + srcImage.getHeight()) / radius1;
        return setRadius(srcImage, radius1, 0, 0);
    }

    public static BufferedImage setClip(BufferedImage srcImage, int radius) {
        int width = srcImage.getWidth();
        int height = srcImage.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D gs = image.createGraphics();

        gs.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        gs.setClip(new RoundRectangle2D.Double(0, 0, width, height, radius, radius));
        gs.drawImage(srcImage, 0, 0, null);
        gs.dispose();
        return image;
    }

    public BufferedImage createImage(String uploadpath, String dirpath, List<PosterDevise> list, ImageInfo info) throws IOException, URISyntaxException, FontFormatException {
        System.out.println(dirpath);


        //  创建画布
        int width = 323;
        int height = 700;
        //    BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        BufferedImage bufferedImage = ImageIO.read(new File(dirpath));
        //  获得画笔
        Graphics g = bufferedImage.getGraphics();


        //   g.drawString("Testttt", 100, 100);

        Iterator<PosterDevise> iterator = list.iterator();
        while (iterator.hasNext()) {
            PosterDevise next = iterator.next();
            if (StringUtils.equals(next.getType(), "image")) {
                switch (next.getKeyName()) {
                    case "avatar":
                        System.out.println(info.getAvatar());
                        g = imageStyle(g, next, getNetUrlHttp(info.getAvatar()));
                        break;
                    case "qrcode":
                     g = imageStyle(g, next, info.getQrcodeFile());
                        break;
                    case "posterImage":
                        g = imageStyle(g, next, new File(uploadpath + "" + info.getPosterImage()));
                        break;
                }
            } else {
                switch (next.getKeyName()) {
                    case "nickname":
                        if (StringUtils.isNotEmpty(info.getNickname())) g = fontStyle(g, next, info.getNickname());
                        break;
                    case "authName":
                        if (StringUtils.isNotEmpty(info.getAuthName())) g = fontStyle(g, next, info.getAuthName());
                        break;
                    case "invite":
                        if (StringUtils.isNotEmpty(info.getInvalid())) g = fontStyle(g, next, info.getInvalid());
                        break;
                    case "price":
                        if (StringUtils.isNotEmpty(String.valueOf(info.getPrice())))
                            g = fontStyle(g, next, String.valueOf(info.getPrice()));
                        break;
                    case "goodName":
                        if (StringUtils.isNotEmpty(info.getGoodName())) g = fontStyle(g, next, info.getGoodName());
                        break;
                    case "title":

                        if (StringUtils.isNotEmpty(info.getTitle())) g = fontStyle(g, next, info.getTitle());
                        break;
                }


            }

        }

        Date date = new Date();
        //  ImageIO.write(bufferedImage, "png", new FileOutputStream("G:/imgaeii/" + date.getTime() + "test.png"));
        return bufferedImage;
    }

    public BufferedImage resizeImage(int x, int y, BufferedImage bfi) {
        BufferedImage bufferedImage = new BufferedImage(x, y, BufferedImage.TYPE_INT_RGB);
        bufferedImage.getGraphics().drawImage(bfi.getScaledInstance(x, y, Image.SCALE_SMOOTH), 0, 0, null);
        return bufferedImage;
    }

    public Graphics fontStyle(Graphics g, PosterDevise poster, String text) throws IOException, FontFormatException {
        System.out.println(poster);
        System.out.println(text);

        Integer fontSize = poster.getFontSize();

        //  Font font =LoadFont.loadFont(fontSize);
//font.deriveFont(Font.BOLD,30f);

        Font font = null;

        if (isChinse(text)) {
            System.out.println("Helllo");
           font = new Font("宋体", Font.BOLD, fontSize);
          //  font = new Font("Microsoft Sans Serif", Font.BOLD, fontSize);
        } else {
          font = new Font("Microsoft Sans Serif", Font.BOLD, fontSize);
          //  font = new Font("宋体", Font.BOLD, fontSize);
        }


        g.setColor(hex2Rgb(poster.getColor() != null ? poster.getColor() : "#000000"));

        g.setFont(font);
        //    g.setColor(Color.red);
        System.out.println(g.getFont());
        g.drawString(text, poster.getX(), poster.getY());
        return g;
    }

    private Color fromStrToARGB(String str) {

        String str1 = str.substring(0, 2);

        String str2 = str.substring(2, 4);

        String str3 = str.substring(4, 6);

        String str4 = str.substring(6, 8);

        int alpha = Integer.parseInt(str1, 16);

        int red = Integer.parseInt(str2, 16);

        int green = Integer.parseInt(str3, 16);

        int blue = Integer.parseInt(str4, 16);

        return new Color(red, green, blue, alpha);

    }

    /**
     * @param colorStr e.g. "#FFFFFF"
     * @return
     */
    public Color hex2Rgb(String colorStr) {
        return new Color(
                Integer.valueOf(colorStr.substring(1, 3), 16),
                Integer.valueOf(colorStr.substring(3, 5), 16),
                Integer.valueOf(colorStr.substring(5, 7), 16));
    }

    public Graphics imageStyle(Graphics g, PosterDevise poster, File file) throws IOException {
       // System.out.println(poster);

        if (file.isFile()) {
            System.out.println(file);
            BufferedImage read = null;
            read = ImageIO.read(file);
            //  g.drawString("Hello Test", poster.getX(), poster.getY());
            if (poster.getRadius() > 0) {
                read = setRadius(read, poster.getRadius());
            } else {
                read = setRadius(read, poster.getRadius());
            }
            g.drawImage(read, poster.getX(), poster.getY(), poster.getW(), poster.getH(), null);
        }
        return g;
    }

    private File toFile(URI uri) {
        File file = new File(uri);
        return file;
    }

    private File getNetUrlHttp(String path) {
        //对本地文件命名，path是http的完整路径，主要得到资源的名字
        String newUrl = path;
        newUrl = newUrl.split("[?]")[0];
        String[] bb = newUrl.split("/");
        //得到最后一个分隔符后的名字
        String fileName = bb[bb.length - 1];
        //保存到本地的路径
        String filePath = "e:\\audio\\" + fileName;
        File file = null;

        URL urlfile;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            //判断文件的父级目录是否存在，不存在则创建
            file = new File(filePath);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            try {
                //创建文件
                file.createNewFile();
            } catch (Exception e) {
                e.printStackTrace();
            }
            //下载
            urlfile = new URL(newUrl);
            inputStream = urlfile.openStream();
            outputStream = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != outputStream) {
                    outputStream.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    private boolean isChinse(String text) {
        String regex = "^[A-z\\u4e00-\\u9fa5·。]*$";
        boolean matches = Pattern.matches(regex, text);
        //   Matcher m = Pattern.compile(regex).matcher(text);

        return matches;
    }

}
